package com.dianrui.fmi.fragment;


import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.BottomSheetDialog;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.dianrui.fmi.Constant;
import com.dianrui.fmi.R;
import com.dianrui.fmi.activity.BigImageActivity;
import com.dianrui.fmi.adapter.QuestionCommentuntyAdapter;
import com.dianrui.fmi.bean.QuestionCommunity;
import com.dianrui.fmi.community.CommuntiyInfoActivity;
import com.dianrui.fmi.event.RfreshAnswer;
import com.dianrui.fmi.event.RfreshCommunity;
import com.dianrui.fmi.event.RfreshFavorites;
import com.dianrui.fmi.event.RfreshQuestion;
import com.dianrui.fmi.interfaces.DeleteCommunityClick;
import com.dianrui.fmi.interfaces.NineAdapter2OperationCallBack;
import com.dianrui.fmi.util.MyUtil;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.ToastUtil;
import com.dianrui.fmi.util.Url;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.fmi.view.pulltoRefresh.PullToRefreshListView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.gson.JsonObject;
import com.twitter.sdk.android.tweetcomposer.TweetComposer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class FragmentMyQuestionCommunity extends BaseFragment implements NineAdapter2OperationCallBack,DeleteCommunityClick {
    private CallbackManager callbackManager;
    private ShareDialog shareDialog;
    private int mPageIndex = 1;
    private QuestionCommentuntyAdapter questionCommentuntyAdapter;
    private List<QuestionCommunity> mQuestionlist = new ArrayList<>();
    private List<String> imageList = new ArrayList<>();

    @BindView(R.id.my_question_list)
    PullToRefreshListView myQuestionList;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;



    @Override
    public int getContentViewId() {
        return R.layout.frag_myquestion_community;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        questionCommentuntyAdapter=new QuestionCommentuntyAdapter(getActivity(),mQuestionlist,this,this);
        myQuestionList.setAdapter(questionCommentuntyAdapter);
        myQuestionList.setMode(PullToRefreshBase.Mode.BOTH);
        getMyQuestion(false);
        questionCommentuntyAdapter.setOnQuestionCommentuntyClickListener(new QuestionCommentuntyAdapter.QuestionClickListener() {

            @Override
            public void ClickMain(String community_id) {//点击整个区域
                startActivity(new Intent(getActivity(),CommuntiyInfoActivity.class).putExtra("community_id",community_id));

            }

            @Override
            public void reply(final String communityId, String memberId) {//回复
                final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(getActivity(), R.style.BottomSheetStyle);
                View view2 = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_input_reply, null);
                final EditText input = view2.findViewById(R.id.reply_content);
                final Button yes_dialog = view2.findViewById(R.id.reply_btn);
                final Button cancel_dialog = view2.findViewById(R.id.cancel_btn);
                input.setHint(getString(R.string.reply));
                input.setMovementMethod(new ScrollingMovementMethod());
                yes_dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtils.isEmpty(input.getText().toString())) {
                            ToastUtil.showToast(getString(R.string.please_input_reply_content));
                        } else {
                            bottomSheetDialog.dismiss();
                            insertComment(input, communityId);
                        }
                    }
                });
                cancel_dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                bottomSheetDialog.setContentView(view2);
                bottomSheetDialog.setCanceledOnTouchOutside(true);
                if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
                    bottomSheetDialog.show();
                }
            }

            @Override
            public void share() {//分享
                final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(getActivity());
                View showThanksMoneyview = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_invite_friends, null);
                Button cancelBtn=showThanksMoneyview.findViewById(R.id.cancel);
                LinearLayout facebookLayout=showThanksMoneyview.findViewById(R.id.facebook_layout);
                LinearLayout twitterLayout=showThanksMoneyview.findViewById(R.id.twitter_layout);
                facebookLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                        if (!MyUtil.checkfackboosInstalled(getActivity())) {
                            ToastUtil.showToast(getString(R.string.please_install_facebook));
                            return;
                        }
                        if (ShareDialog.canShow(ShareLinkContent.class)) {
                            ShareLinkContent linkContent = new ShareLinkContent.Builder()
                                    .setContentUrl(Uri.parse("https://developers.facebook.com"))
                                    .build();
                            shareDialog.show(linkContent);
                        }
                    }
                });
                twitterLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                        if (!MyUtil.checkfackboosInstalled(getActivity())) {
                            ToastUtil.showToast(getString(R.string.please_install_twitter));
                            return;
                        }
                        try {
                            TweetComposer.Builder builder = new TweetComposer.Builder(getActivity())
                                    .url(new URL("https://www.google.com/"));
                            builder.show();
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    }
                });
                cancelBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomSheetDialog.dismiss();
                    }
                });
                bottomSheetDialog.setContentView(showThanksMoneyview);
                bottomSheetDialog.setCanceledOnTouchOutside(true);
                if (!MyUtil.getActivity(bottomSheetDialog.getContext()).isFinishing()) {
                    bottomSheetDialog.show();
                }
            }

            @Override
            public void like(int pos,String community_id, ImageView imageView) {//点赞
                CommunityCollect(pos,community_id, imageView);

            }
        });
        myQuestionList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMyQuestion(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mPageIndex++;
                getMyQuestion(false);

            }
        });
        initFacebook();

    }

    @Override
    public void getData() {}


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshQuestion rfreshQuestion) {
        getMyQuestion(true);

    }

    //获取我的问题
    private void getMyQuestion(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("p", mPageIndex);
        jsonObject.addProperty("type", "2");
        OkHttpUtils.getInstance().postWithMemberToken(Url.COMMUNITY, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (myQuestionList != null) {
                    myQuestionList.onRefreshComplete();
                }
                if (isRfresh) {
                    mQuestionlist.clear();
                }

                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray data = jsonObject.optJSONArray("data");
                                if (null != data &&data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        QuestionCommunity questionCommunity = new QuestionCommunity();
                                        questionCommunity.community_id = data.optJSONObject(i).optString("community_id");
                                        questionCommunity.contents = data.optJSONObject(i).optString("contents");
                                        questionCommunity.create_time = data.optJSONObject(i).optString("create_time");
                                        questionCommunity.member_id = data.optJSONObject(i).optString("member_id");
                                        questionCommunity.nickname = data.optJSONObject(i).optString("nickname");
                                        questionCommunity.face = data.optJSONObject(i).optString("face");
                                        questionCommunity.comment_number = data.optJSONObject(i).optString("comment_number");
                                        questionCommunity.share_number = data.optJSONObject(i).optString("share_number");
                                        questionCommunity.collect_number = data.optJSONObject(i).optString("collect_number");
                                        questionCommunity.is_collect = data.optJSONObject(i).optInt("is_collect");
                                        JSONArray jsonArray1 = data.optJSONObject(i).optJSONArray("picture");
                                        List<String> picList = new ArrayList<>();
                                        for (int j = 0; j < jsonArray1.length(); j++) {
                                            picList.add(jsonArray1.optString(j));
                                        }
                                        questionCommunity.picture = picList;
                                        mQuestionlist.add(questionCommunity);
                                    }
                                    if (questionCommentuntyAdapter != null) {
                                        questionCommentuntyAdapter.refresh(mQuestionlist);
                                    }

                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (mQuestionlist.size() <= 0) {
                        emptyView.setVisibility(View.VISIBLE);
                        myQuestionList.setVisibility(View.GONE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        myQuestionList.setVisibility(View.VISIBLE);
                    }

                } else {
                    if (myQuestionList != null) {
                        myQuestionList.onRefreshComplete();
                    }
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    //收藏
    private void CommunityCollect(final int poistion, String community_id, final ImageView imageView) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("collect_id", community_id);
        OkHttpUtils.getInstance().postWithMemberToken(Url.COLLECT, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (null != jsonObject && isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                mQuestionlist.get(poistion).is_collect = jsonObject.getJSONObject("data").optInt("is_collect");
                                if (jsonObject.getJSONObject("data").optInt("is_collect")==1) {
                                    mQuestionlist.get(poistion).collect_number = String.valueOf(Integer.valueOf(mQuestionlist.get(poistion).collect_number) + 1);
                                    imageView.setImageResource(R.mipmap.collected);
                                    EventBus.getDefault().post(new RfreshFavorites());
                                    EventBus.getDefault().post(new RfreshCommunity());
                                    EventBus.getDefault().post(new RfreshQuestion());
                                    EventBus.getDefault().post(new RfreshAnswer());
                                } else {
                                    mQuestionlist.get(poistion).collect_number = String.valueOf(Integer.valueOf(mQuestionlist.get(poistion).collect_number) - 1);
                                    imageView.setImageResource(R.mipmap.uncollected);
                                    EventBus.getDefault().post(new RfreshFavorites());
                                    EventBus.getDefault().post(new RfreshCommunity());
                                    EventBus.getDefault().post(new RfreshQuestion());
                                    EventBus.getDefault().post(new RfreshAnswer());
                                }
                                questionCommentuntyAdapter.refresh(mQuestionlist);

                            } else {

                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {

                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });

    }


    private void insertComment(EditText input, String communityId) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", communityId);
        jsonObject.addProperty("contents", input.getText().toString().trim());
        OkHttpUtils.getInstance().postWithMemberToken(Url.INSERTCOMMON, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                EventBus.getDefault().post(new RfreshFavorites());
                                EventBus.getDefault().post(new RfreshCommunity());
                                EventBus.getDefault().post(new RfreshQuestion());
                                EventBus.getDefault().post(new RfreshAnswer());
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * facebook配置
     */
    private void initFacebook() {
        callbackManager = CallbackManager.Factory.create();
        shareDialog = new ShareDialog(this);
        // this part is optional
        shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {

            @Override
            public void onSuccess(Sharer.Result result) {
                //分享成功的回调，在这里做一些自己的逻辑处理
                ToastUtil.showToast("Share Success");
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //facebook的界面回调
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }



    @Override
    public void onClickImage(int position, String url, List<String> urlList) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < urlList.size(); i++) {
            temp.add(urlList.get(i));
        }
        startActivity(new Intent(getActivity(), BigImageActivity.class)
                .putStringArrayListExtra("data", (ArrayList<String>) temp)
                .putExtra("current", position));
    }



    @Override
    public void DeleteCommunityClick(String community_id) {
        DeleteComment(community_id);
    }

    private void DeleteComment(String community_id) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("community_id", community_id);
        OkHttpUtils.getInstance().postWithMemberToken(Url.DELTECOMMENT, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                 getMyQuestion(true);
                                EventBus.getDefault().post(new RfreshFavorites());
                                EventBus.getDefault().post(new RfreshCommunity());
                                EventBus.getDefault().post(new RfreshQuestion());
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
